import { reqGoodsDetail } from '@/api/goods'
import { userBehavior } from '@/behaviors/userBehavior'
import { reqAddToCart, reqCartList } from '@/api/cart'

const app = getApp()
Page({
  behaviors: [userBehavior],
  // 页面的初始数据
  // 页面的初始数据
  data: {
    isIos: false,
    navBarHeight: 0, //导航栏高度
    titleBarHeight: 0, //标题栏
    show: false,
    goodsId: '', //商品id
    goodsInfo: {},
    count: 1, //商品数量
    blessing: '',
    totalCount: 0, //购物车总商品数
    isAddToCartBtn: false //区分点击了加入购物车还是立即购买按钮
  },

  async getGoodsInfo() {
    const { data } = await reqGoodsDetail(this.data.goodsId)
    this.setData({
      goodsInfo: data
    })
  },

  goBack() {
    wx.navigateBack()
  },
  onClickGoHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  onClickGoDetail() {
    wx.switchTab({
      url: '/pages/shoppingCard/shoppingCard'
    })
  },

  previewImg() {
    wx.previewImage({
      urls: this.data.goodsInfo.detailList
    })
  },
  // 加购物车
  onClickAddToCart() {
    this.setData({
      show: true,
      isAddToCartBtn: true
    })
  },

  onClickToBuy() {
    this.setData({
      show: true,
      isAddToCartBtn: false
    })
  },

  onChangeCount(e) {
    this.setData({
      count: e.detail
    })
  },

  // 确定
  async confirmBtn() {
    const { goodsId, count, blessing, isAddToCartBtn, token } = this.data
    // 先判断用户是否已登录
    if (!token) {
      wx.navigateTo({
        url: '/pages/login/login'
      })
      return
    }
    if (isAddToCartBtn) {
      const res = await reqAddToCart({ goodsId, count, blessing })
      if (res.code === 200) {
        wx.toast({ title: '加入购物车成功' })
        this.getCartTotalCount()
      }
    } else {
      wx.navigateTo({
        url: `/modules/orderModule/pages/order/order-detail/order-detail?goodsId=${goodsId}&blessing=${blessing}`
      })
    }
    this.setData({
      show: false
    })
  },

  // 获取购物车总商品数
  async getCartTotalCount() {
    const { token } = this.data
    if (!token) return
    const { code, data } = await reqCartList()
    if (code === 200) {
      if (data.length) {
        const totalCount = data.reduce((prev, current) => prev + current.count, 0)
        this.setData({
          totalCount: totalCount > 99 ? '99+' : totalCount
        })
      }
    }
  },

  onClose() {
    this.setData({
      show: false
    })
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    const { goodsId } = options
    if (!goodsId) return
    this.setData({
      goodsId,
      navBarHeight: app.globalData.navBarHeight,
      isIos: app.globalData.isIos,
      titleBarHeight: app.globalData.titleBarHeight
    })
    this.getGoodsInfo()
    this.getCartTotalCount()
  },

  onShareAppMessage: function () {
    const { goodsInfo, goodsId } = this.data
    return {
      title: goodsInfo.name,
      path: `/modules/goodsModule/pages/goods-detail/goods-detail?goodsId=${goodsId}`,
      imageUrl: goodsInfo.imageUrl
    }
  },
  onShareTimeline: function () {}
})
